package com.xipu.yygh.hosp.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.common.result.R;
import com.xipu.yygh.hosp.service.HospitalSetService;
import com.xipu.yygh.model.hosp.HospitalSet;
import com.xipu.yygh.vo.hosp.HospitalSetQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * <p>
 * 医院设置表 前端控制器
 * </p>
 *
 * @author gql
 * @since 2022-04-17
 */
@Api(tags = "医院设置管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/hosp/hospitalSet")
public class HospitalSetController {

    private final HospitalSetService hospitalSetService;

    @ApiOperation("C-医院设置信息")
    @PostMapping("saveHospitalSet")
    public R save(@RequestBody HospitalSet hospitalSet) {
        // 后端校验
        if (null == hospitalSet.getHosname() || null == hospitalSet.getHoscode()
                || null == hospitalSet.getApiUrl()
                || null == hospitalSet.getContactsName()
                || null == hospitalSet.getContactsPhone()) {
            return R.error().message("存在未填项");
        }

        hospitalSet.setStatus(1);
        //签名秘钥
        Random random = new Random();
        //hospitalSet.setSignKey(MD5.encrypt(System.currentTimeMillis() + "" + random.nextInt(1000)));
        boolean flag = false;
        try {
            flag = hospitalSetService.save(hospitalSet);
        } catch (Exception e) {
            return R.error().message("医院编号被占用");
        }
        if (flag) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    @GetMapping("findAll")
    @ApiOperation("R-医院设置列表")
    public R findAll() {
        List<HospitalSet> list = this.hospitalSetService.list();
        return R.ok().data("rows", list);
    }

    @GetMapping("findPage/{current}/{limit}")
    @ApiOperation("R-医院设置列表,分页")
    public R findPage(@PathVariable Long current, @PathVariable Long limit) {
        // 创建Page对象
        Page<HospitalSet> page = new Page<>(current, limit);
        // 封装分页数据
        hospitalSetService.page(page, null);
        // 获取记录和总记录数
        long total = page.getTotal();
        List<HospitalSet> list = page.getRecords();
        return R.ok().data("total", total).data("rows", list);
    }

    @ApiOperation("R-医院设置列表,条件查询带分页")
    @PostMapping("findPageQuery/{currentPage}/{limit}")
    public R findPageQuery(
            @PathVariable Long currentPage,
            @PathVariable Long limit,
            @RequestBody(required = false) HospitalSetQueryVo hospitalSetQueryVo) {
        // 创建分页对象page
        Page<HospitalSet> page = new Page<>(currentPage, limit);
        LambdaQueryWrapper<HospitalSet> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(HospitalSet::getHoscode);
        // 根据医院编号升序排列(数据库表字段是varchar...so,wft?)
        // 封装分页数据和查询条件
        if (null == hospitalSetQueryVo) {
            this.hospitalSetService.page(page, queryWrapper);
        } else {
            String hosname = hospitalSetQueryVo.getHosname();
            String hoscode = hospitalSetQueryVo.getHoscode();
            if (!StringUtils.isEmpty(hosname)) {
                queryWrapper.like(HospitalSet::getHosname, hosname);
            }
            if (!StringUtils.isEmpty(hoscode)) {
                queryWrapper.eq(HospitalSet::getHoscode, hoscode);
            }
            this.hospitalSetService.page(page, queryWrapper);
        }
        // 获取总记录数total
        long total = page.getTotal();
        // 获取当前页数据集合
        List<HospitalSet> records = page.getRecords();
        // 3.返回数据
        return R.ok().data("total", total).data("rows", records);
    }


    @ApiOperation("R-根据ID查询医院设置")
    @GetMapping("getHospSet/{id}")
    public R getHospSetById(@PathVariable String id) {
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        return R.ok().data("hospitalSet", hospitalSet);
    }

    @ApiOperation("U-根据ID修改医院设置")
    @PostMapping("updateHospSet")
    public R updateHospSet(@RequestBody HospitalSet hospitalSet) {
        boolean flag = false;
        try {
            flag = hospitalSetService.updateById(hospitalSet);
        } catch (Exception e) {
            throw new YyghException(20001, "医院编号重复！");
        }
        if (flag) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }
    }

    /**
     * 更新医院设置表status字段思路:
     *      1. 根据id查询医院设置信息
     *      2. 设置status状态
     *      3. 根据id更新医院设置信息
     * @param id
     * @param status
     * @return
     */
    @ApiOperation("U-更新医院设置表的status字段")
    @PutMapping("lockHospitalSet/{id}/{status}")
    public R lockHospitalSet(@PathVariable Long id,
                             @PathVariable Integer status) {
        //根据id查询医院设置信息
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        //设置状态
        hospitalSet.setStatus(status);
        //调用方法
        hospitalSetService.updateById(hospitalSet);
        return R.ok();
    }

    @DeleteMapping("remove/{id}")
    @ApiOperation("D-根据id删除医院设置信息")
    public R removeHospSet(@PathVariable Long id) {
        boolean flag = this.hospitalSetService.removeById(id);
        if (flag) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    @ApiOperation("D-批量删除医院设置信息")
    @DeleteMapping("batchRemove")
    public R batchRemoveHospitalSet(@RequestBody List<Long> idList) {
        boolean flag = hospitalSetService.removeByIds(idList);
        if (flag) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    @ApiOperation("a. 模拟异常")
    @GetMapping("testException")
    public R testException() {
        // 为了测试,模拟异常
        try {
            int i = 10 / 0;
        } catch (Exception e) {
            // 抛出自定义异常
            throw new YyghException(20001, "执行自定义异常处理");
        }
        return R.ok().data("msg", "模拟异常");
    }
}

